# encoding=utf8
# !/usr/bin/python
import datetime
import time
import paho.mqtt.client as mqtt
import ssl
ssl.match_hostname = lambda cert, hostname: True
from mysqlUtils import PdbcUtil
from Filter import filter, filterUtils
class DataProcessor():
    def __init__(self):
        self.rhFilterQueue = []
        self.co2FilterQueue = []
        self.tvocFilterQueue = []
        self.lightFilterQueue=[]
        self.lastSentTime = time.time()


    def sendCommand(self, cmd: str):

        f = self.mqttClient.publish('control', cmd, 1)
        if (self.mqttClient._inflight_messages > 0):  # 我也不知道这个库为什么会犯这个毛病，总之似乎不太对劲……
            self.mqttClient._inflight_messages -= 1

        self.lastSentTime = time.time()


    def continousFiltering(self,rh,temp,light):

        #l = row.strip().split(',')
        #print(l)
        #temp = temp
        #rh = rh
        #light = float(l[2])

        rh, self.rhFilterQueue = filterUtils(rh, self.rhFilterQueue, r=2 * 10 ** -3, q=8 * 10 ** -5)
        light, self.lightFilterQueue = filterUtils(light, self.lightFilterQueue, r=10 ** -4.2, q=10 ** -5.2)
        print(self.rhFilterQueue)
        print(self.lightFilterQueue)
        return temp, rh, light




class MyMqttClient(mqtt.Client):
    def __init__(self, clientId="", cleanSession=None, userData=None,
                 protocol=4, transport="tcp"):
        super(MyMqttClient, self).__init__(client_id=clientId, clean_session=cleanSession, userdata=userData
                                           , protocol=4, transport="tcp")
        self.queue=None
        # self.strBroker = "117.51.142.180"  # 服务器地址
        self.strBroker='117.73.10.122'
        self.port = 1883#2883
        self.topic = clientId
        print('开始连接远程服务器……')
        #user=

        # self.tls_set(ca_certs='ca.crt')
        self.connect(self.strBroker, self.port, 60)
        print("设备启动完成")
        self.subscribe('#', 0)
        self.mysqlUtil=PdbcUtil()
        self.dataProcessor=DataProcessor()




    def on_connect(self, aa, mqttC, obj, rc):
        # super().on_connect()
        print("OnConnetc, rc: " + str(rc))

    def on_publish(self, mqttC, obj, mid):
        # super().on_publish()
        print("OnPublish, mid: " + str(mid))

    def on_subscribe(self, mqttC, obj, mid, granted_qos):
        # super().on_subscribe()
        print("Subscribed: " + str(mid) + " " + str(granted_qos))

    def on_log(self, mqttC, obj, level, string):
        print("Log:" + string)

    def on_message(self, mqttc, obj, msg):
        # super().on_message()
        curtime = datetime.datetime.now()
        strCurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
        print(strCurtime + ": " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
        print(msg.payload,msg.payload.decode('utf-8'))
        s=msg.payload.decode('utf-8')

       

            
        #l1=s.split(':')
        #sensorId=l1[0].strip()
        l2=s.strip().split(',')
        f = open("log.csv", "a")
        f.write(s+'\n')
        f.close()
        RH=float(l2[0])
        temp=float(l2[1])
        light=float(l2[2])
        print(l2,RH,temp,light)
        temp,RH,light=self.dataProcessor.continousFiltering(RH,temp,light)
        self.mysqlUtil.insertData2(sensorId="sensor",RH=RH,temp=temp,light=light)

        self.mysqlUtil.insertLog(topic=msg.topic, message=msg.payload.decode('utf-8'), qos=msg.qos)
        



if __name__ == '__main__':
    m = MyMqttClient('test')
    m.loop_forever()
